package com.lry.handler;

import com.lry.bean.ExceptionNotice;
import com.lry.bean.HttpExceptionNotice;
import com.lry.event.ExceptionNoticeEvent;
import com.lry.properties.EaProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;

import java.util.Map;

@Slf4j
public class DefaultExceptionHandler implements ExceptionHandler{

    private EaProperties eaProperties;

    private ApplicationEventPublisher publisher;


    public DefaultExceptionHandler(EaProperties eaProperties, ApplicationEventPublisher publisher) {
        this.eaProperties = eaProperties;
        this.publisher = publisher;
    }

    @Override
    public ExceptionNotice createNotice(RuntimeException e, String methodName, Object[] args) {

        ExceptionNotice exceptionNotice = new ExceptionNotice(e, args,  eaProperties.getName() );

        log.debug("创建异常通知：" + methodName);

        publisher.publishEvent(new ExceptionNoticeEvent(this, exceptionNotice));

        return exceptionNotice;
    }

    @Override
    public HttpExceptionNotice createHttpNotice(RuntimeException exception, String url, Map<String, String> param,
                                                String requestBody, Map<String, String> headers) {
        log.debug("创建异常通知：" + url);
        HttpExceptionNotice exceptionNotice = new HttpExceptionNotice(exception, url, param, requestBody, headers,
                String.format("%s的异常通知", eaProperties.getName()));

        exceptionNotice.setProject(eaProperties.getName());
        publisher.publishEvent(new ExceptionNoticeEvent(this, exceptionNotice));
        return exceptionNotice;
    }

}
